package com.oneday.ashop.webgate.base.spring;

import com.oneday.ashop.core.entity.User;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登陆过滤器
 * //TODO 杨波 代码显得有点冗余，有待优化
 * User:bob.yang
 * Date 2015/8/13 0013
 */
public class LoginFilter extends OncePerRequestFilter{

    //静态资源
    //TODO 杨波 暂时这么弄，后面可以加到配置文件中
    public static final String[] staticResource = {"/css/", "/fonts/", "/images/", "/js/", "/jquery/"};

    //无需登陆的即可访问的资源
    public static final String[] noAuthorResource = {"/page/user/protocol.jsp", "/page/user/login.jsp", "/user/login.htm",
            "/user/get_register.htm", "/user/register.htm", "/error.html"};

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

//        //获得请求的上下文
        String uri = request.getServletPath();
        //登陆判断
        if(check(uri)) {
            filterChain.doFilter(request, response);
        }else {
            //对于需要登陆的资源进行判断，发现未登录直接返回登陆页面
            HttpSession session = request.getSession();
            User user = (User)session.getAttribute("user");
            if(user == null) {
                response.sendRedirect("../user/login.htm");
                return;
            }else {
                filterChain.doFilter(request, response);
                return;
            }
        }
    }

    /**
     * 判断uri是否请求的是静态资源/判断uri是否请求不需要登陆的资源
     * @param uri
     * @return
     */
    public boolean check(String uri) {
        for(String temp : staticResource) {
            if(uri.startsWith(temp)) {
                return true;
            }
        }
        for(String temp : noAuthorResource) {
            if(uri.equals(temp)) {
                return true;
            }
        }
        return false;
    }
}
